import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import '../../../main.dart'; // 导入全局navigatorKey
import '../home/home_page.dart';
import 'register_step1_page.dart';
import 'test_info_page.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  // 手机号登录控制器
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  // 账号密码登录控制器
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  // 验证码倒计时状态
  CountdownButtonState _countdownState = CountdownButtonState.normal;

  // 密码可见性
  bool _isPasswordVisible = false;

  late StreamSubscription<List<ConnectivityResult>>? _connectivitySubscription;
  bool _isShowingOfflineSnackbar = false;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    // 设置默认显示账号密码登录
    _tabController.index = 1;
    _checkPendingRegistration();
    // 检查自动登录
    _checkAutoLogin();

    // 监听网络连接变化
    _connectivitySubscription = Connectivity().onConnectivityChanged.listen(
      (List<ConnectivityResult> result) {
        if (result.contains(ConnectivityResult.none) &&
            !_isShowingOfflineSnackbar) {
          _isShowingOfflineSnackbar = true;
          _showErrorSnackBar('网络连接已断开，请检查网络设置');
        } else if (!result.contains(ConnectivityResult.none) &&
            _isShowingOfflineSnackbar) {
          _isShowingOfflineSnackbar = false;
          _showSuccessSnackBar('网络连接已恢复');
        }
      },
    );
  }

  /// 检查自动登录
  Future<void> _checkAutoLogin() async {
    try {
      // 检查是否有保存的token
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString('auth_token');

      if (token == null || token.isEmpty) {
        Logger.d('AUTO_LOGIN', '没有保存的token，需要手动登录');
        return;
      }

      Logger.d('AUTO_LOGIN', '发现保存的token，开始验证...');

      // 检查网络连接
      final isConnected = await ApiService().checkNetworkConnection();
      if (!isConnected) {
        Logger.w('AUTO_LOGIN', '网络未连接，跳过自动登录');
        return;
      }

      // 获取用户ID
      final userId = await ApiService().getUserId();
      if (userId == null) {
        Logger.w('AUTO_LOGIN', '没有保存的用户ID，清除token');
        await _clearAuthData();
        return;
      }

      if (userId.isEmpty) {
        Logger.w('AUTO_LOGIN', '用户ID为空，清除token');
        await _clearAuthData();
        return;
      }

      // 尝试获取用户信息来验证token
      try {
        Logger.d('AUTO_LOGIN', '验证token，用户ID: $userId');
        final profile = await ApiService().getUserProfile(userId);

        // 如果成功获取用户信息，说明token有效，自动登录
        Logger.d('AUTO_LOGIN', 'Token验证成功，自动登录');
        Logger.d('AUTO_LOGIN', '用户信息: ${profile.username}');

        // 延迟一下，确保UI已经渲染完成
        if (mounted) {
          await Future.delayed(const Duration(milliseconds: 500));
          if (mounted) {
            _loginSuccess();
          }
        }
      } catch (e) {
        // token无效，清除保存的认证信息
        Logger.w('AUTO_LOGIN', 'Token验证失败: $e，清除认证信息');
        await _clearAuthData();
      }
    } catch (e) {
      Logger.e('AUTO_LOGIN', '自动登录检查失败: $e');
      // 出错时清除可能无效的认证信息
      await _clearAuthData();
    }
  }

  /// 清除认证数据
  Future<void> _clearAuthData() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('auth_token');
      await prefs.remove('user_id');
      Logger.d('AUTO_LOGIN', '已清除认证信息');
    } catch (e) {
      Logger.e('AUTO_LOGIN', '清除认证信息失败: $e');
    }
  }

  Future<void> _checkPendingRegistration() async {
    final prefs = await SharedPreferences.getInstance();
    final pending = prefs.getBool('pending_registration') ?? false;
    if (pending) {
      final phone = prefs.getString('pending_phone');
      final code = prefs.getString('pending_code');
      if (phone != null && code != null && mounted) {
        // 直接跳转到完善信息页
        WidgetsBinding.instance.addPostFrameCallback((_) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => RegisterStep1Page(),
            ),
          );
        });
      }
    }
  }

  @override
  void dispose() {
    _connectivitySubscription?.cancel();
    _tabController.dispose();
    _phoneController.dispose();
    _codeController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  // 手机号验证码登录
  void _loginWithPhone() async {
    final phone = _phoneController.text;
    final code = _codeController.text;

    if (phone.isEmpty) {
      _showErrorSnackBar('请输入手机号');
      return;
    }

    if (!_isValidPhoneNumber(phone)) {
      _showErrorSnackBar('手机号格式不正确');
      return;
    }

    if (code.isEmpty) {
      _showErrorSnackBar('请输入验证码');
      return;
    }

    // 检查网络连接
    final connectivityResult = await Connectivity().checkConnectivity();
    if (connectivityResult == ConnectivityResult.none) {
      _showErrorSnackBar('网络连接不可用，请检查网络设置');
      return;
    }

    // 显示加载状态
    _showLoadingDialog();

    try {
      // 调用API进行登录
      final result = await ApiService().loginWithPhone(
        phone: phone,
        code: code,
      );

      // 登录成功后，保存token
      // 从日志看，API返回的token可能在data.accessToken字段中
      if (result.containsKey('data') && result['data'] != null) {
        final data = result['data'];
        if (data.containsKey('accessToken')) {
          await ApiService().setAuthToken(data['accessToken']);
        } else if (data.containsKey('token')) {
          await ApiService().setAuthToken(data['token']);
        }
      } else if (result.containsKey('token')) {
        await ApiService().setAuthToken(result['token']);
      }

      Navigator.of(context).pop(); // 关闭加载对话框
      _loginSuccess();
    } catch (e) {
      Navigator.of(context).pop(); // 关闭加载对话框
      _showErrorSnackBar(e.toString());
    }
  }

  // 账号密码登录
  void _loginWithPassword() async {
    final username = _usernameController.text;
    final password = _passwordController.text;

    if (username.isEmpty) {
      _showErrorSnackBar('请输入账号');
      return;
    }

    if (password.isEmpty) {
      _showErrorSnackBar('请输入密码');
      return;
    }

    // 检查网络连接
    final connectivityResult = await Connectivity().checkConnectivity();
    if (connectivityResult == ConnectivityResult.none) {
      _showErrorSnackBar('网络连接不可用，请检查网络设置');
      return;
    }

    // 显示加载状态
    _showLoadingDialog();

    try {
      // 调用API进行登录
      final result = await ApiService().loginWithPassword(
        username: username,
        password: password,
      );

      // 使用Logger记录API返回结果，设置为debug级别
      Logger.d('LOGIN_API', '=== API Login Response ===');
      Logger.d('LOGIN_API', 'Result data: $result');
      Logger.d('LOGIN_API', 'Result type: ${result.runtimeType}');
      Logger.d(
          'LOGIN_API', 'Contains success: ${result.containsKey('success')}');
      if (result.containsKey('success')) {
        Logger.d('LOGIN_API', 'Success value: ${result['success']}');
      }
      Logger.d('LOGIN_API', 'Contains data: ${result.containsKey('data')}');
      if (result.containsKey('data')) {
        Logger.d('LOGIN_API', 'Data value: ${result['data']}');
        Logger.d('LOGIN_API', 'Data type: ${result['data'].runtimeType}');
      }

      // 登录成功后，保存token和用户ID
      bool tokenSaved = false;
      if (result.containsKey('data') && result['data'] != null) {
        final data = result['data'];
        if (data.containsKey('accessToken')) {
          Logger.d('LOGIN_AUTH', 'Saving accessToken');
          await ApiService().setAuthToken(data['accessToken']);
          tokenSaved = true;
        } else if (data.containsKey('token')) {
          Logger.d('LOGIN_AUTH', 'Saving token');
          await ApiService().setAuthToken(data['token']);
          tokenSaved = true;
        } else {
          Logger.w('LOGIN_AUTH', 'No token found in data object');
        }

        // 保存用户ID（如果存在）
        if (data.containsKey('userId')) {
          Logger.d('LOGIN_AUTH', 'Saving userId: ${data['userId']}');
          await ApiService().setUserId(data['userId'].toString());
        } else if (data.containsKey('id')) {
          Logger.d('LOGIN_AUTH', 'Saving id as userId: ${data['id']}');
          await ApiService().setUserId(data['id'].toString());
        } else {
          Logger.w('LOGIN_AUTH', 'No userId found in data object');
        }
      } else if (result.containsKey('token')) {
        Logger.d('LOGIN_AUTH', 'Saving root token');
        await ApiService().setAuthToken(result['token']);
        tokenSaved = true;

        // 保存用户ID（如果存在）
        if (result.containsKey('userId')) {
          Logger.d('LOGIN_AUTH', 'Saving userId: ${result['userId']}');
          await ApiService().setUserId(result['userId'].toString());
        } else if (result.containsKey('id')) {
          Logger.d('LOGIN_AUTH', 'Saving id as userId: ${result['id']}');
          await ApiService().setUserId(result['id'].toString());
        }
      } else {
        Logger.w('LOGIN_AUTH', 'No token found in response');
      }

      Logger.d('LOGIN_AUTH', 'Token saved: $tokenSaved');

      Navigator.of(context).pop(); // 关闭加载对话框
      Logger.d('LOGIN_FLOW', 'Login dialog closed');

      // 检查当前UI上下文状态
      Logger.d(
          'LOGIN_FLOW', 'Before calling _loginSuccess - isMounted: $mounted');

      // 使用WidgetsBinding确保在UI线程中执行导航
      Logger.d('LOGIN_FLOW', 'Scheduling _loginSuccess on WidgetsBinding');
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Logger.d('LOGIN_FLOW',
            'WidgetsBinding callback executing _loginSuccess - time: ${DateTime.now()}');
        if (mounted) {
          Logger.d(
              'LOGIN_FLOW', 'Context is still valid, calling _loginSuccess()');
          _loginSuccess();
        } else {
          Logger.e('LOGIN_FLOW',
              'Context is no longer valid when trying to call _loginSuccess()');
          // 如果上下文无效，尝试使用全局方式显示错误消息
          try {
            final overlay = Overlay.of(context, rootOverlay: true);
            overlay.insert(OverlayEntry(
                builder: (context) => const ScaffoldMessenger(
                    child: Material(
                        child: SnackBar(content: Text('登录成功但无法导航，请重试'))))));
          } catch (e) {
            Logger.e('LOGIN_FLOW', '无法显示错误消息: $e');
          }
        }
      });
    } catch (e) {
      Navigator.of(context).pop(); // 关闭加载对话框
      Logger.e('LOGIN_ERROR', 'Login error', exception: e as Exception);
      _showErrorSnackBar(e.toString());
    }
  }

  // 发送验证码
  void _sendVerificationCode() async {
    final phone = _phoneController.text;

    if (phone.isEmpty) {
      _showErrorSnackBar('请输入手机号');
      return;
    }

    if (!_isValidPhoneNumber(phone)) {
      _showErrorSnackBar('手机号格式不正确');
      return;
    }

    // 检查网络连接
    final connectivityResult = await Connectivity().checkConnectivity();
    if (connectivityResult == ConnectivityResult.none) {
      _showErrorSnackBar('网络连接不可用，请检查网络设置');
      return;
    }

    // 显示加载状态
    setState(() {
      _countdownState = CountdownButtonState.sending;
    });

    try {
      // 调用API发送验证码（purpose=login）
      await ApiService().sendVerificationCode(phone, 'login');

      // 发送成功，开始倒计时
      setState(() {
        _countdownState = CountdownButtonState.countdown;
      });

      _showSuccessSnackBar('验证码已发送');
    } catch (e) {
      setState(() {
        _countdownState = CountdownButtonState.normal;
      });
      _showErrorSnackBar(e.toString());
    }
  }

  // 显示加载对话框
  void _showLoadingDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: Card(
          elevation: 4,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(12)),
          ),
          child: Padding(
            padding: EdgeInsets.all(24.0),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                CircularProgressIndicator(),
                SizedBox(width: 16),
                Text('正在处理...', style: TextStyle(fontSize: 16)),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 验证码倒计时结束
  void _onCountdownEnd() {
    setState(() {
      _countdownState = CountdownButtonState.normal;
    });
  }

  // 登录成功处理 - 简化版
  void _loginSuccess() {
    Logger.i('LOGIN_SUCCESS', '登录成功，准备跳转到主页');
    Logger.d('LOGIN_SUCCESS', '准备跳转 - 时间: ${DateTime.now()}');
    _showSuccessSnackBar('登录成功');

    // 隐藏键盘
    _hideKeyboard();

    // 使用WidgetsBinding确保在下一帧执行导航，避免上下文问题
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Logger.d('LOGIN_SUCCESS', 'WidgetsBinding回调执行 - 时间: ${DateTime.now()}');
      if (mounted) {
        try {
          Logger.d('LOGIN_SUCCESS', '开始执行导航到主页');
          Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(
                builder: (context) => const HomePage(initialIndex: 0)),
            (Route<dynamic> route) => false,
          );
          Logger.d('LOGIN_SUCCESS', '导航成功');
        } catch (e) {
          Logger.e('LOGIN_SUCCESS', '导航失败', exception: e as Exception);
          // 如果普通导航失败，尝试使用全局导航键
          _fallbackNavigation();
        }
      } else {
        Logger.w('LOGIN_SUCCESS', 'Widget已卸载，使用备用导航');
        _fallbackNavigation();
      }
    });
  }

  // 备用导航方法
  void _fallbackNavigation() {
    try {
      if (navigatorKey.currentState != null) {
        navigatorKey.currentState!.pushAndRemoveUntil(
          MaterialPageRoute(builder: (_) => const HomePage(initialIndex: 0)),
          (route) => false,
        );
        Logger.d('LOGIN_NAV', '全局导航键导航成功');
      } else {
        _showErrorSnackBar('登录成功，但无法跳转到主页！\n请点击底部的测试按钮直接进入主页');
      }
    } catch (e) {
      Logger.e('LOGIN_NAV', '备用导航也失败', exception: e as Exception);
      _showErrorSnackBar('登录成功，但无法跳转到主页！\n请点击底部的测试按钮直接进入主页');
    }
  }

  // 跳转到注册页面
  void _navigateToRegister() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const RegisterStep1Page()),
    );
  }

  // 跳转到测试信息页面
  void _navigateToTestInfo() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const TestInfoPage()),
    );
  }

  // 验证手机号格式
  bool _isValidPhoneNumber(String phone) {
    return RegExp(r'^1[3-9]\d{9}$').hasMatch(phone);
  }

  // 隐藏键盘
  void _hideKeyboard() {
    FocusScope.of(context).requestFocus(FocusNode());
  }

  // 显示错误提示
  void _showErrorSnackBar(String message) {
    // 去除错误消息中的Exception前缀
    String displayMessage = message;
    if (message.startsWith('Exception:')) {
      displayMessage = message.substring('Exception:'.length).trim();
    }

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(displayMessage),
        backgroundColor: Colors.red,
        duration: const Duration(seconds: 3), // 延长显示时间
        action: SnackBarAction(
          label: '知道了',
          textColor: Colors.white,
          onPressed: () {
            ScaffoldMessenger.of(context).hideCurrentSnackBar();
          },
        ),
      ),
    );
  }

  // 显示成功提示
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: GestureDetector(
        onTap: _hideKeyboard, // 点击空白处隐藏键盘
        child: SafeArea(
          child: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 32.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                const SizedBox(height: 40),

                // Logo和标题
                _buildHeader(),

                const SizedBox(height: 24),

                // 登录方式切换标签
                _buildTabBar(),

                const SizedBox(height: 16),

                // 登录表单（减小高度，避免无界约束）
                SizedBox(
                  height: 350, // 减小表单高度
                  child: TabBarView(
                    controller: _tabController,
                    children: [
                      _buildPhoneLoginForm(),
                      _buildPasswordLoginForm(),
                    ],
                  ),
                ),

                const SizedBox(height: 8), // 减小间距

                // 注册按钮
                _buildRegisterButton(),

                const SizedBox(height: 8), // 减小间距

                // 测试信息按钮
                _buildTestInfoButton(),

                const SizedBox(height: 8), // 减小间距

                // 直接跳转按钮
                _buildDirectNavigateButton(),

                const SizedBox(height: 16), // 减小底部间距
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Column(
      children: [
        // Logo
        Container(
          width: 80,
          height: 80,
          decoration: BoxDecoration(
            color: Theme.of(context).primaryColor,
            borderRadius: BorderRadius.circular(20),
          ),
          child: const Icon(
            Icons.person,
            color: Colors.white,
            size: 40,
          ),
        ),
        const SizedBox(height: 20),
        const Text(
          '欢迎使用',
          style: TextStyle(
            fontSize: 28,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 8),
        const Text(
          '请选择登录方式',
          style: TextStyle(
            fontSize: 16,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  Widget _buildTabBar() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey[200],
        borderRadius: BorderRadius.circular(25),
      ),
      child: TabBar(
        controller: _tabController,
        indicator: BoxDecoration(
          color: Theme.of(context).primaryColor,
          borderRadius: BorderRadius.circular(25),
        ),
        labelColor: Colors.white,
        unselectedLabelColor: Colors.grey[600],
        labelStyle: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w500,
        ),
        unselectedLabelStyle: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w500,
        ),
        tabs: const [
          Tab(text: '手机号登录'),
          Tab(text: '账号密码'),
        ],
      ),
    );
  }

  Widget _buildPhoneLoginForm() {
    return Column(
      children: [
        // 手机号输入框
        Container(
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(12),
          ),
          child: TextField(
            controller: _phoneController,
            keyboardType: TextInputType.phone,
            decoration: const InputDecoration(
              hintText: '请输入手机号',
              prefixIcon: Icon(Icons.phone),
              border: InputBorder.none,
              contentPadding:
                  EdgeInsets.symmetric(horizontal: 16, vertical: 16),
            ),
          ),
        ),

        const SizedBox(height: 16),

        // 验证码输入框
        Row(
          children: [
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: TextField(
                  controller: _codeController,
                  keyboardType: TextInputType.number,
                  maxLength: 6,
                  decoration: const InputDecoration(
                    hintText: '请输入验证码',
                    prefixIcon: Icon(Icons.security),
                    border: InputBorder.none,
                    contentPadding:
                        EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                    counterText: '',
                  ),
                ),
              ),
            ),
            const SizedBox(width: 12),
            CountdownButton(
              state: _countdownState,
              onPressed: _sendVerificationCode,
              onEnd: _onCountdownEnd,
            ),
          ],
        ),

        const SizedBox(height: 32),

        // 登录按钮
        SizedBox(
          width: double.infinity,
          height: 50,
          child: ElevatedButton(
            onPressed: _loginWithPhone,
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).primaryColor,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
            child: const Text(
              '登录',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildPasswordLoginForm() {
    return Column(
      children: [
        // 账号输入框
        Container(
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(12),
          ),
          child: TextField(
            controller: _usernameController,
            decoration: const InputDecoration(
              hintText: '请输入账号',
              prefixIcon: Icon(Icons.person),
              border: InputBorder.none,
              contentPadding:
                  EdgeInsets.symmetric(horizontal: 16, vertical: 16),
            ),
          ),
        ),

        const SizedBox(height: 16),

        // 密码输入框
        Container(
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(12),
          ),
          child: TextField(
            controller: _passwordController,
            obscureText: !_isPasswordVisible,
            decoration: InputDecoration(
              hintText: '请输入密码',
              prefixIcon: const Icon(Icons.lock),
              suffixIcon: IconButton(
                icon: Icon(
                  _isPasswordVisible ? Icons.visibility : Icons.visibility_off,
                ),
                onPressed: () {
                  setState(() {
                    _isPasswordVisible = !_isPasswordVisible;
                  });
                },
              ),
              border: InputBorder.none,
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
            ),
          ),
        ),

        const SizedBox(height: 32),

        // 登录按钮
        SizedBox(
          width: double.infinity,
          height: 50,
          child: ElevatedButton(
            onPressed: _loginWithPassword,
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).primaryColor,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
            child: const Text(
              '登录',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildRegisterButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Text(
          '还没有账号？',
          style: TextStyle(
            fontSize: 16,
            color: Colors.grey,
          ),
        ),
        TextButton(
          onPressed: _navigateToRegister,
          child: Text(
            '立即注册',
            style: TextStyle(
              fontSize: 16,
              color: Theme.of(context).primaryColor,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildTestInfoButton() {
    return Center(
      child: TextButton.icon(
        onPressed: _navigateToTestInfo,
        icon: const Icon(Icons.info_outline, size: 16),
        label: const Text(
          '查看测试账号信息',
          style: TextStyle(fontSize: 14),
        ),
      ),
    );
  }

  // 直接跳转到主页按钮
  Widget _buildDirectNavigateButton() {
    return SizedBox(
      width: double.infinity,
      height: 48,
      child: ElevatedButton(
        onPressed: _directNavigateToHome,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.orange,
          foregroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        child: const Text(
          '直接进入主页（测试用）',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }

  // 直接跳转到主页 - 简化版
  void _directNavigateToHome() {
    _showSuccessSnackBar('跳过登录直接进入主页');
    Logger.d('DIRECT_NAV', '开始导航');

    // 使用WidgetsBinding确保在下一帧执行导航
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        try {
          Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(
                builder: (context) => const HomePage(initialIndex: 0)),
            (Route<dynamic> route) => false,
          );
          Logger.d('DIRECT_NAV', '导航成功');
        } catch (e) {
          Logger.e('DIRECT_NAV', '导航失败', exception: e as Exception);
          _fallbackNavigation();
        }
      } else {
        _fallbackNavigation();
      }
    });
  }
}
